﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Windows.Forms;

using DevExpress.XtraEditors.Controls;
using DevExpress.XtraTab;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraEditors;
using MINERP.BLL.InfoConfig;
using MINERP.DAL;
using MINERP.MODEL.InfoConfig;

namespace MINERP.InfoConfig.Controller
{

    public class UsersController
    {
        #region //private fields

        private UserBLL _bll = new UserBLL();
        private List<users> _listUsers = new List<users>();
        private GridControl _grid = null;
        private GridView _view = null;
        private ComboBoxEdit _comboBox = null;
        private GroupControl _groupControl = null;
        private CheckEdit _checkEdit = null;
        private CheckedComboBoxEdit _checkComboBoxEdit = null;
        private XtraTabControl _xtraTabControl = null;
        private XtraTabControl _xtraTabControlAction = null;
        private List<tb_Power> _powerList = null;
        private List<tb_WorkerGroup> _groupList = null;
        private List<tb_Action> _actionList = null;
        private List<tb_Tech> _techList = new List<tb_Tech>();
        private CheckEdit[] checkEdit = null;
        private List<CheckEdit> _checkEditList = new List<CheckEdit>();
        #endregion

        public UsersController()
        {
        }

        #region //public Priorities
        internal XtraTabControl XtraTabControl
        {
            set
            {
                _xtraTabControl = value;
            }
        }

        internal XtraTabControl XtraTabControlAction
        {
            set
            {
                _xtraTabControlAction = value;
            }
        }

        internal CheckedComboBoxEdit CheckedComboBoxEdit
        {
            set
            {
                _checkComboBoxEdit = value;
            }
        }
        internal GroupControl GroupControl
        {
            set
            {
                _groupControl = value;
            }
        }
        internal CheckEdit CheckEdit
        {
            set
            {
                _checkEdit = value;
            }
        }
        internal ComboBoxEdit ComoBox
        {
            set
            {
                _comboBox = value;
            }
        }
        internal GridControl Grid
        {
            set
            {
                _grid = value;
            }
        }

        internal GridView View
        {
            set
            {
                this._view = value;
            }
            get
            {
                return _view;
            }
        }
        #endregion

        #region//public methods
        /// <summary>
        /// 动态创建操作CheckEdit
        /// </summary>
        /// <param name="obj"></param>
        public void CreateConctrols(int userId)
        {
            users user;
            List<string> listActionName = new List<string>();
            using (newSampleYPDBEntities enty = new newSampleYPDBEntities())
            {
                user = enty.users.FirstOrDefault(u => u.userID == userId);
                if (!user.tb_Action.IsLoaded)
                {
                    user.tb_Action.Load();
                }

            }
            foreach (var item in user.tb_Action)
	        {
        		 listActionName.Add( item.ActionName);
	        }
            _xtraTabControlAction.TabPages.Clear();
            List<CheckedListBoxItem> list = new List<CheckedListBoxItem>();
            if (_checkComboBoxEdit != null)
            {
                foreach (CheckedListBoxItem item in _checkComboBoxEdit.Properties.Items)
                {
                    if (item.CheckState == CheckState.Checked)
                    {
                        list.Add(item);
                    }
                }
            }
            for (int i = 0; i < list.Count; i++)
            {
                _xtraTabControlAction.TabPages.Add(list[i].Value.ToString());
                tb_Power power = _bll.GetPowetObj(list[i].Value.ToString());
                _actionList = _bll.GetActionList(power);
                checkEdit = new CheckEdit[_actionList.Count];
                _xtraTabControlAction.TabPages[i].AutoScroll = true;
                int left = 10;
                int top = 10;
                bool newRow = false;

                for (int j = 0; j < _actionList.Count; j++)
                {
                    checkEdit[j] = new CheckEdit();
                    checkEdit[j].Name = "checkEdit" + j;
                    checkEdit[j].Width = 115;

                    if (left >= _xtraTabControlAction.Width)
                    {
                        newRow = true;
                    }
                    if (newRow)
                    {
                        newRow = false;
                        left = 10;
                        top += checkEdit[j].Height;
                    }

                    checkEdit[j].Left = left;
                    checkEdit[j].Top = top;
                    left += checkEdit[j].Width;

                    checkEdit[j].Text = _actionList[j].ActionName;
                    if(listActionName.Contains(_actionList[j].ActionName))
                    {
                        checkEdit[j].Checked = false;
                    }
                    else
                    {
                        checkEdit[j].Checked = true;
                    }
                    _xtraTabControlAction.TabPages[i].Controls.Add(checkEdit[j]);

                }
            }
        }
        /// <summary>
        /// 生成节点控件
        /// </summary>
        public void CreateConctrolsTechs()
        {

            _xtraTabControl.TabPages.Clear();
            List<CheckedListBoxItem> list = new List<CheckedListBoxItem>();
            if (_checkComboBoxEdit != null)
            {
                foreach (CheckedListBoxItem item in _checkComboBoxEdit.Properties.Items)
                {
                    if (item.CheckState ==  CheckState.Checked)
                    {
                        list.Add(item);
                    }
                }
            }
            for (int i = 0; i < list.Count; i++)
            {
                _xtraTabControl.TabPages.Add(list[i].Value.ToString());
                tb_Power power = _bll.GetPowetObj(list[i].Value.ToString());
                //_actionList = _bll.GetActionList(power);
                List<tb_Tech> listTech = new List<tb_Tech>();
                if (!power.tb_Tech.IsLoaded)
                {
                    power.tb_Tech.Load();
                }
                foreach (var item in power.tb_Tech)
                {
                    listTech.Add(item);
                }
                checkEdit = new CheckEdit[listTech.Count];
                for (int j = 0; j < listTech.Count; j++)
                {
                    int x = 10;
                    int y = 10;
                    checkEdit[j] = new CheckEdit();
                    checkEdit[j].Name = "checkEdit" + j;
                    checkEdit[j].Left = x + checkEdit[j].Width * j;
                    checkEdit[j].Top = y;
                    //if (checkEdit[j].Left >= _xtraTabControl.TabPages[i].Width)
                    //{
                    //    checkEdit[j].Top = y + checkEdit[j].Height * j;
                    //}
                    checkEdit[j].Text = listTech[j].TechName;
                    checkEdit[j].Checked = true;
                    _checkEditList.Add(checkEdit[j]);
                    checkEdit[j].CheckedChanged += new EventHandler(UsersController_CheckedChanged);
                    _xtraTabControl.TabPages[i].Controls.Add(checkEdit[j]);

                }
            }
        }
        /// <summary>
        /// 动态创建单个用户所属权限checkEdit
        /// </summary>
        /// <param name="obj"></param>
        public void CreateConctrolsOfUser(users obj)
        {
            List<tb_Action> userActionlist = new List<tb_Action>();
            _powerList = new List<tb_Power>();
            users userAndPowers = _bll.GetUserAndPower(obj);
            foreach (tb_Power power in userAndPowers.tb_Power)
            {
                _powerList.Add(power);
            }
            _xtraTabControlAction.TabPages.Clear();
            for (int i = 0; i < _powerList.Count; i++)
            {
                _actionList = new List<tb_Action>();
                _xtraTabControlAction.TabPages.Add(_powerList[i].Name);
                _xtraTabControlAction.TabPages[i].AutoScroll = true;
                List<tb_Action> powerActionList = new List<tb_Action>();
                powerActionList = _bll.GetActionList(_powerList[i]);
                foreach (tb_Action action in _bll.GetUserAndAction(obj).tb_Action)
                {
                    userActionlist.Add(action);
                }
                foreach (var item in powerActionList)
                {
                    if (!userActionlist.Contains(item, new c()))
                        _actionList.Add(item);
                }
                checkEdit = new CheckEdit[powerActionList.Count];
                int left = 10;
                int top = 10;
                bool newRow = false;
                for (int j = 0; j < powerActionList.Count; j++)
                {
                    checkEdit[j] = new CheckEdit();
                    checkEdit[j].Name = "checkEdit" + j;
                    checkEdit[j].Width = 115;

                    if (left >= _xtraTabControlAction.Width)
                    {
                        newRow = true;
                    }
                    if (newRow)
                    {
                        left = 10;
                        top += checkEdit[j].Height;
                        newRow = false;
                    }

                    checkEdit[j].Left = left;
                    checkEdit[j].Top = top;
                    left += checkEdit[j].Width;

                    checkEdit[j].Text = powerActionList[j].ActionName;
                    if (!userActionlist.Contains(powerActionList[j], new c()))
                    {
                        checkEdit[j].Checked = true;
                    }
                    else
                    {
                        checkEdit[j].Checked = false;
                    }

                    _xtraTabControlAction.TabPages[i].Controls.Add(checkEdit[j]);

                }
            }

        }

        /// <summary>
        /// 动态创建单个用户所能操作的节点checkEdit
        /// </summary>
        /// <param name="obj"></param>
        public void CreateConctrolTechsOfUser(users user)
        {
            using (newSampleYPDBEntities entities = new newSampleYPDBEntities())
            {
                users obj = entities.users.FirstOrDefault(u => u.userID == user.userID);
                List<tb_Tech> techList = new List<tb_Tech>();
                List<tb_Tech> listUserTech = new List<tb_Tech>();
                List<tb_Tech> listPowerTech = new List<tb_Tech>();
                List<tb_Power> listPower = new List<tb_Power>();
                if (!obj.tb_Power.IsLoaded)
                {
                    obj.tb_Power.Load();
                }
                if (!obj.tb_Tech.IsLoaded)
                {
                    obj.tb_Tech.Load();
                }
                foreach (var item in obj.tb_Power)
                {
                    listPower.Add(item);
                }
                foreach (var item in obj.tb_Tech)
                {
                    listUserTech.Add(item);
                }

                _xtraTabControl.TabPages.Clear();
                for (int i = 0; i < listPower.Count; i++)
                {
                    listPowerTech.Clear();
                    techList.Clear();
                    if (!listPower[i].tb_Tech.IsLoaded)
                    {
                        listPower[i].tb_Tech.Load();
                    }
                    foreach (var item in listPower[i].tb_Tech)
                    {
                        listPowerTech.Add(item);
                    }
                    _xtraTabControl.TabPages.Add(listPower[i].Name);

                    foreach (var item in listUserTech)
                    {
                        if (listPowerTech.Contains(item, new d()))
                            techList.Add(item);
                    }
                    checkEdit = new CheckEdit[listPowerTech.Count];
                    for (int j = 0; j < listPowerTech.Count; j++)
                    {
                        int x = 10;
                        int y = 10;
                        checkEdit[j] = new CheckEdit();
                        checkEdit[j].Name = "checkEdit" + j;
                        checkEdit[j].Left = x + checkEdit[j].Width * j;
                        checkEdit[j].Top = y;

                        checkEdit[j].Text = listPowerTech[j].TechName;
                        if (listUserTech.Contains(listPowerTech[j], new d()))
                        {
                            checkEdit[j].Checked = true;
                        }
                        else
                        {
                            checkEdit[j].Checked = false;
                        }
                        checkEdit[j].CheckedChanged += new EventHandler(UsersController_CheckedChanged);
                        _xtraTabControl.TabPages[i].Controls.Add(checkEdit[j]);

                    }
                }

            }
        }
        /// <summary>
        /// 获得控件上的所有节点
        /// </summary>
        /// <returns></returns>
        public List<tb_Tech> GetTechList()
        {
            _techList.Clear();
            TechBLL techBLL = new TechBLL();
            for (int i = 0; i < _xtraTabControl.TabPages.Count; i++)
            {
                foreach (CheckEdit item in _xtraTabControl.TabPages[i].Controls)
                {
                    if (item.Checked)
                    {
                        tb_Tech tech = techBLL.GetTechObj(item.Text);
                        _techList.Add(tech);
                    }
                }
            }
            return _techList;
        }

        private List<tb_Action> GetActionList()
        {
            List<tb_Action> list = new List<tb_Action>();

            for (int i = 0; i < _xtraTabControlAction.TabPages.Count; i++)
            {
                List<tb_Action> TempList = new List<tb_Action>();
                tb_Power power = _bll.GetPowetObj(_xtraTabControlAction.TabPages[i].Text);
                if (!power.tb_Action.IsLoaded)
                {
                    power.tb_Action.Load();
                }
                foreach (var item in power.tb_Action)
                {
                    TempList.Add(item);
                }
                foreach (CheckEdit item in _xtraTabControlAction.TabPages[i].Controls)
                {
                    if (!item.Checked)
                    {
                        tb_Action action = _bll.GetActionObj(item.Text);
                        if (TempList.Contains(action, new c()))
                        {
                            list.Add(action);
                        }
                    }
                }
            }

            return list;
        }

        public class c : IEqualityComparer<tb_Action>
        {
            public bool Equals(tb_Action x, tb_Action y)
            {
                if (x.ActionId == y.ActionId)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }

            public int GetHashCode(tb_Action a)
            {
                return 0;
            }
        }
        public class d : IEqualityComparer<tb_Tech>
        {
            public bool Equals(tb_Tech x, tb_Tech y)
            {
                if (x.TechId == y.TechId)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }

            public int GetHashCode(tb_Tech a)
            {
                return 0;
            }
        }
        /// <summary>
        /// 获得单个用户的操作权限
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private List<tb_Action> GetActionList(users obj)
        {
            List<tb_Action> list = new List<tb_Action>();
            users user = _bll.GetUserAndAction(obj);
            foreach (tb_Action action in user.tb_Action)
            {
                list.Add(action);
            }
            return list;
        }
        /// <summary>
        /// 获得默认数据
        /// </summary>
        public void GetDefaultData()
        {
            this._grid.DataSource = _bll.GetUserList();
        }
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="obj"></param>
        public void AddUser(users obj, List<CheckedListBoxItem> roleList, string groupName)
        {

            List<tb_Power> powerList = new List<tb_Power>();
            for (int i = 0; i < roleList.Count; i++)
            {
                powerList.Add(_bll.GetPowetObj(roleList[i].Value.ToString()));
            }
            List<tb_Action> actionList = GetActionList();

            _bll.AddUser(obj, actionList, _techList, powerList, groupName);

        }

        /// <summary>
        /// 检查用户是否已经存在，存在返加TURE，不存在返回FALSE
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool checkUserIsIn(string loginName)
        {
            var a = _bll.GetUserByUserName(loginName);
            if (a == null)
            {
                return false;
            }
            else
            {
                return true;
            }        
        }

        /// <summary>
        /// 更新用户
        /// </summary>
        /// <param name="obj"></param>
        public int UpdateUser(users obj, List<CheckedListBoxItem> roleList, string groupName)
        {
            List<tb_Power> powerList = new List<tb_Power>();
            for (int i = 0; i < roleList.Count; i++)
            {
                powerList.Add(_bll.GetPowetObj(roleList[i].Value.ToString()));
            }
            List<tb_Action> actionList = GetActionList();
            return _bll.UpdateUser(obj, actionList, _techList, powerList, groupName);
        }
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="obj"></param>
        public void DeleteUser(users obj)
        {
            _bll.DeleteUser(obj);
        }
        /// <summary>
        /// 绑定用户角色
        /// </summary>
        public void LinkchkcmbRole()
        {
            _powerList = _bll.GetPowerList();
            _checkComboBoxEdit.Properties.Items.Clear();
            _checkComboBoxEdit.Text = "请选择角色....";
            foreach (var power in _powerList)
            {
                _checkComboBoxEdit.Properties.Items.Add(power.Name);
            }
        }
        /// <summary>
        /// 绑定用户组
        /// </summary>
        public void LinkUserGroup()
        {
            _groupList = _bll.GetGroupList();
            _comboBox.Properties.Items.Clear();
            foreach (var group in _groupList)
            {
                _comboBox.Properties.Items.Add(group.GroupName);
            }
        }

        public users GetUserObj(int id)
        {
            return _bll.GetUserObj(id);
        }

        private void UsersController_CheckedChanged(object sender, EventArgs e)
        {
            _xtraTabControl = (XtraTabControl)((CheckEdit)sender).Parent.Parent;
            GetTechList();
        }
        #endregion
    }
}
